﻿function InitVEdit()
{
	//全局变量
	var isMouseDown = false;
	var lang;
	var dict;
	var doc;
	var style = "";
	var veTemplatePath;
	var veImagePath;
	var curCss;
	var widgetCounter;
	var textCounter;
	var cssPath;
	var status = "Play";
	
	//闪烁插入位置
	var Blink = function(element)
	{
		if (element.is(":hidden"))
		{
			if (typeof(element.data("TimerID")) != "undefined")
				clearInterval(element.data("TimerID"));
			element.removeData("TimerID");
			return;
		}

		var colorIndex = 0;
		if (typeof(element.data("ColorIndex")) != "undefined")
			colorIndex = element.data("ColorIndex");
		if (colorIndex > 2)
			colorIndex = 0;
	
		var color = "#F00";
		if (colorIndex == 1)
			color = "#0F0";
		else if (colorIndex == 2)
			color = "#00F";
	
		colorIndex++;
		element.css("border-color", color);
		element.data("ColorIndex", colorIndex)
		if (typeof(element.data("TimerID")) == "undefined")
			element.data("TimerID", setInterval(function(){Blink(element);}, 500));
	};
	
	//绑定widget的事件
	var BindWidget = function(widgets)
	{
		widgets.droppable(
		{
			over:function(e, ui)
			{
				//如果源Widget与目标Widget，则不能拖动
				if (ui.helper.data("Source").index(this) != -1)
					return;
				
				//如果源Widget不能包含在目标Widget父元素内，则不能拖动
				var container;
				if (typeof(ui.helper.data("Source").attr("container")) == "undefined")
					container = ui.helper.data("Source").parent();
				else
					container = $(ui.helper.data("Source").attr("container"));
				if (container.index($(this).parent()) == -1)
					return;
				
				//如果目标Widget是源Widget的父元素，则不能拖动
				if ($(this).find("widget").index(ui.helper.data("Source")) != -1)
					return;
	
				ui.helper.data("Target", $(this));
			},
			out:function(e, ui)
			{
				if (typeof(ui.helper.data("Target")) != "undefined")
					ui.helper.removeData("Target");
					
				$("#WidgetIndicator").hide();
			},
			drop:function(e, ui)
			{
				if (ui.helper.data("Source").index(this) != -1 || typeof(ui.helper.data("Position")) == "undefined")
					return;

				//获取doc处理所需变量
				var targetID = ui.helper.data("Target").attr("id");
				var sourceID = ui.helper.data("Source").attr("id");
				var targetRe = new RegExp("(<!-- TemplateBeginEditable name=\".*\" -->\\s*)?<widget id=\"" + targetID + "\"(.|\\s)*?</widget>(\\s*<!-- TemplateEndEditable -->)?", "g");
				var target = targetRe.exec(doc);
				var sourceRe = new RegExp("(<!-- TemplateBeginEditable name=\".*\" -->\\s*)?<widget id=\"" + sourceID + "\"(.|\\s)*?</widget>(\\s*<!-- TemplateEndEditable -->)?", "g");
				var source = sourceRe.exec(doc);
				
				//源再后面时，提前删除掉
				if (target.index < source.index)
					doc = doc.substr(0, source.index) + doc.substr(source.index + source[0].length);

				//视图和文档实现插入
				if (ui.helper.data("Position") == "Before")
				{
					ui.helper.data("Source").insertBefore(ui.helper.data("Target"));
					
					doc = doc.substr(0, target.index) + source[0] + doc.substr(target.index);
				}
				else
				{
					ui.helper.data("Source").insertAfter(ui.helper.data("Target"));
					
					doc = doc.substr(0, target.index + target[0].length) + source[0] + doc.substr(target.index + target[0].length);
				}
				
				//源在前面时，删除掉
				if (target.index > source.index)
					doc = doc.substr(0, source.index) + doc.substr(source.index + source[0].length);
			}
		}).mouseenter(function()
		{
			if (isMouseDown || status != "Play")
				return;
	
			var w = $(this).width();
			var h = $(this).height();
			var t = $(this).position().top - 1;
			var l = $(this).position().left - 1;
			$("#WidgetSelect").data("Source", $(this)).show().stop().animate({width:w,height:h,top:t,left:l}, "fast");
		}).mouseleave(function(e)
		{
			$("#WidgetIndicator").hide();
	
			if (isMouseDown)
				return;
	
			var b = $("#WidgetSelect");
			if (e.pageY < b.position().top || e.pageY > b.position().top + b.height() || e.pageX < b.position().left || e.pageX > b.position().left + b.width())
				b.hide();
		});
	};
	
	//绑定text的事件
	var BindText = function(texts)
	{
		$("body").delegate("text", "click", function()
		{
			status = "Edit";
			this.contentEditable = true;
			this.focus();
			return false;
		});
		
		$("body").delegate("text", "blur", function()
		{
			this.contentEditable = false;
			if ($("#WidgetPause").attr("src").indexOf("play") != -1)
				status = "Pause";
			else
				status = "Play";
			
			var startTag = "<text id=\"" + this.id + "\">";
			var endTag = "</text>";
			var re = new RegExp(startTag + "(.|\\s)*?" + endTag);
			var result = re.exec(doc);
			doc = doc.substr(0, result.index + startTag.length) + $(this).html() + doc.substr(result.index + result[0].length - endTag.length);
		});
	}
	
	//绑定WidgetSelect的事件
	var BindWidgetSelect = function(widgetSelect)
	{
		widgetSelect.draggable(
		{
			delay:500,
			drag : function(e, ui)
			{
				if (typeof(ui.helper.data("Target")) == "undefined")
					return;
				
				var target = ui.helper.data("Target");
				var w = target.width();
				var h = target.height();
				var t = target.position().top;
				var l = target.position().left;
				
				var insert = $("#WidgetIndicator");
				ui.helper.removeData("Position");
				if (e.pageY < t + h / 2)
				{
					t = t - insert.height() - 2 * parseInt(insert.css("border-top-width"));
					
					//如果上面的Widget是被拖动的Widget，则不处理
					if (ui.helper.data("Source").index(ui.helper.data("Target").prev("widget")) != -1)
					{
						insert.hide();
						return;
					}
	
					ui.helper.data("Position", "Before");
				}
				else
				{
					t = t + h;
					
					//如果下面的Widget是被拖动的Widget，则不处理
					if (ui.helper.data("Source").index(ui.helper.data("Target").next("widget")) != -1)
					{
						insert.hide();
						return;
					}
	
					ui.helper.data("Position", "After");
				}
				
				if (t + insert.height() < 0)
					t = 0;
	
				insert.css({top:t,left:l,width:w});
				if (insert.is(":hidden"))
				{
					insert.show();
					Blink(insert);
				}
			}
		}).mousedown(function(e)
		{
			//如果是text标签上被点击了，进入编辑
			if (typeof($(this).data("Source")) != "undefined" && $(this).data("Source")[0].tagName == "TEXT")
			{
				$(this).data("Source").click();
				$(this).removeData("Source");
				$(this).hide();
				$("#WidgetTool").hide();
				return;
			}

			isMouseDown = true;
			var w = 60;
			var h = 60;
			
			$("#WidgetTool").hide();
			$(this).stop().animate({width:w,height:h,top:e.pageY - h / 2,left:e.pageX - w / 2}, "fast");
		}).mouseup(function()
		{
			isMouseDown = false;
			$(this).hide();
		}).mousemove(function(e)
		{
			if (!isMouseDown)
			{
				//如果当前Widget有子Widget，并且鼠标在它子Widget上面，则源Widget改为子Widget
				$(this).data("Source").find("widget,text").each(function()
				{
					var me = $(this);
					var w = me.width();
					var h = me.height();
					var t = me.position().top;
					var l = me.position().left;
					if (e.pageX > l && e.pageX < l + w && e.pageY > t && e.pageY < t + h)
					{
						$("#WidgetSelect").data("Source", me).stop().animate({width:w,height:h,top:t,left:l}, "fast");
						return false;
					}
				});
			
				//工具菜单跟着鼠标移动
				var tool = $("#WidgetTool");
				if ($(this).data("Source")[0].tagName == "WIDGET")
				{
					var w = tool.width();
					var h = tool.height();
					var t = tool.position().top;
					var l = tool.position().left;
					if (tool.is(":hidden") || (e.pageX < l - 20 || e.pageX > l + w + 20 || e.pageY < t - 20 || e.pageY > t + h + 20))
					{
						if ($(this).data("Source").attr("Json") == undefined)
							$("#WidgetEdit").hide();
						else
							$("#WidgetEdit").show();

						tool.css({top:e.pageY + 10,left:e.pageX - tool.width() / 2}).show();
					}
					$(this).css("cursor", "Move");
				}
				else
				{
					tool.hide();
					$(this).css("cursor", "Text");
				}
			}
		}).mouseleave(function(e)
		{
			//如果正在拖拽，不能隐藏
			if (isMouseDown)
				return;
	
			//如果鼠标在工具上，不能隐藏
			var tool = $("#WidgetTool");
			var w = tool.width();
			var h = tool.height();
			var t = tool.position().top;
			var l = tool.position().left;
			if (e.pageX > l && e.pageX < l + w && e.pageY > t - 10 && e.pageY < t + h)
				return;
	
			$(this).hide();
			$("#WidgetIndicator").hide();
			tool.hide();
		});
	};
	
	//加载模板页面
	var LoadTemplate = function()
	{
		var _LoadTemplate = function()
		{
			$.ajax(
			{
				url : _veChannelPath + "ajax_load.aspx?Original=" + encodeURIComponent(_veOrgPage) + "&Current=" + encodeURIComponent(_veCurPage),
				type : "GET",
				error : function(request)
				{
					if (request.status == 404)
						Alert(dict.find("Word[Name=config_file_not_exist] " + lang).text());
					else
						Alert(dict.find("Word[Name=operation_fail] " + lang).text());
				},
				success : function(data)
				{
					doc = data;
					
					//获取widget.css中的class和id值
					var ids = [];
					var re = /\*\s*Start:([\w-]+)\{ID:"([\w-]+)",/g;
					var w;
					while ((w = re.exec(style)) != null)
						ids.push({Class:w[1],ID:w[2]});
					
					//设置文档widget的id和guid
					var text = "<widget";
					widgetCounter = 1;
					var i = doc.length;
					var ii = i;
					while ((i = doc.lastIndexOf(text, i)) != -1)
					{
						var guid = "";
						var m = doc.substr(i, ii - i).match(/<widget.*class="([\w-]+)".*?>/);
						if (m != null)
						{
							for (var j = 0; j < ids.length; j++)
							{
								if (m[1].indexOf(ids[j].Class) != -1)
								{
									guid = " guid=\"" + ids[j].ID + "\"";
									break;
								}
							}
						}

						doc = doc.substr(0, i + text.length) + " id=\"_w" + (widgetCounter++) + "\"" + guid + doc.substr(i + text.length);
						ii = i;
						i--;
					}
					
					//设置页面widget的id和guid
					var widgets = $("widget");
					var id = 1;
					for (var i = widgets.length - 1; i >= 0; i--)
					{
						widgets.eq(i).attr("id", "_w" + (id++));
						for (var j = 0; j < ids.length; j++)
						{
							if (widgets.eq(i).hasClass(ids[j].Class))
							{
								widgets.eq(i).attr("guid", ids[j].ID);
								break;
							}
						}
					}
					
					//设置文档text标签的id
					text = "<text>";
					textCounter = 1;
					i = doc.length;
					while ((i = doc.lastIndexOf(text, i)) != -1)
					{
						doc = doc.substr(0, i + text.length - 1) + " id=\"_t" + (textCounter++) + "\"" + doc.substr(i + text.length - 1);
						i--;
					}
					
					//设置页面text的id
					var texts = $("text");
					id = 1;
					for (var i = texts.length - 1; i >= 0; i--)
					{
						texts.eq(i).attr("id", "_t" + (id++));
					}
				}
			});
		};

		$.ajax(
		{
			url : cssPath,
			type : "GET",
			error : _LoadTemplate,
			success : function(data)
			{
				style = data;
				_LoadTemplate();
			}
		});
	};
	
	//加载词典
	var LoadDict = function()
	{
		$.ajax(
		{
			url : veTemplatePath + "dict.xml",
			type : "GET",
			error : function(request)
			{
				Alert(request.status);
			},
			success : function(data)
			{
				dict = $(data);
				
				$("#WidgetInsert").attr("title", dict.find("Word[Name=insert] " + lang).text());
				$("#WidgetDelete").attr("title", dict.find("Word[Name=delete] " + lang).text());
				$("#WidgetPause").attr("title", dict.find("Word[Name=pause] " + lang).text());
				$("#WidgetRevert").attr("title", dict.find("Word[Name=revert] " + lang).text());
				$("#WidgetSave").attr("title", dict.find("Word[Name=save] " + lang).text());
				$("#WidgetEdit").attr("title", dict.find("Word[Name=edit] " + lang).text());
			}
		});
	};
	
	//加载css
	var LoadCss = function()
	{
		var curCssPath = _curImagePath.replace(/\/\image\/$/, "/") + "css/common.css";

		$.ajax(
		{
			url : curCssPath,
			type : "GET",
			success : function(data)
			{
				curCss = data;
			}
		});
	};
	
	//弹出属性对话框（插入或者编辑）
	var ShowPropertyDialog = function(id)
	{
		var title;
		if (id != null)
		{
			id = "&ID=" + id;
			title = dict.find("Word[Name=edit] " + lang).text();
		}
		else
		{
			id = "";
			title = dict.find("Word[Name=insert] " + lang).text();
		}

		var html = "<iframe id='InsertDialogFrame' src='" + _veChannelPath + "index.aspx?Skin=" + _curImagePath.replace(/\/\image\/$/, "/") + id + "' style='width:100%;height:450px;border:0;overflow:hidden'></iframe>";
		$("#InsertDialog").html(html).dialog(
		{
			modal:true,
			title:title,
			draggable:true,
			resizable:false,
			width:550,
			height:530,
			buttons:
			{
				"Ok":function()
				{
					var result;
					if ($.browser.msie)
						result = document.frames["InsertDialogFrame"].BuildResult();
					else
						result = document.getElementById("InsertDialogFrame").contentWindow.BuildResult();
					
					//本皮肤该Widget，则需添加Widget的css代码
					var className = result.Widget.ID;
					var curSkin = _curImagePath.replace(/\/\image\/$/, "/");
					var b = result.Widget.Skin != curSkin;
					if (!b)
					{
						var re = new RegExp("/\\*\\s*Start:(\\w+)\\{ID:\"" + result.Widget.ID + "\"(.|\\s)*?/\\*\\s*End:\\1\\s*\\*/", "g");
						var m = re.exec(curCss);
						if (m != null)
							className = m[1];
						else
							b = true;
					}
					if (b)
					{
						if (style.indexOf(result.Widget.ID) == -1)
						{
							$("body").append("<style>" + result.Style + "</style>");
							style += "\r\n/* Start:" + result.Widget.ID + "{ID:\"" + result.Widget.ID + "\",Name:\"" + result.Widget.Name + "\",Width:\"" + result.Widget.Width + "\"} */" + result.Style + "/* End:" + result.Widget.ID + " */";
						}
					}
					
					var targetWidget = $("#WidgetSelect").data("Source");
					var targetID = targetWidget.attr("id");
					var targetRe = new RegExp("(<!-- TemplateBeginEditable name=\".*\" -->\\s*)?<widget id=\"" + targetID + "\"(.|\\s)*?</widget>(\\s*<!-- TemplateEndEditable -->)?", "g");
					var target = targetRe.exec(doc);

					var html = result.Html;
					
					//给页面中text标签加上id
					text = "<text>";
					var counter = textCounter;
					var i = html.length;
					while ((i = html.lastIndexOf(text, i)) != -1)
					{
						html = html.substr(0, i + text.length - 1) + " id=\"_t" + (counter++) + "\"" + html.substr(i + text.length - 1);
						i--;
					}
					
					//给文档中text标签加上id
					counter = textCounter;
					i = result.ServerCode.length;
					while ((i = result.ServerCode.lastIndexOf(text, i)) != -1)
					{
						result.ServerCode = result.ServerCode.substr(0, i + text.length - 1) + " id=\"_t" + (counter++) + "\"" + result.ServerCode.substr(i + text.length - 1);
						i--;
					}

					//
					var widgetText = "<widget id=\"_w" + (widgetCounter++) + "\" guid=\"" + result.Widget.ID + "\" class=\"" + className + "\" json=\"" + escape(result.Json) + "\">{#Content#}</widget>";
					var widget = $(widgetText.replace("{#Content#}", html));
					if (result.Insert == "Before")
					{
						widget.insertBefore(targetWidget);
						doc = doc.substr(0, target.index) + widgetText.replace("{#Content#}", result.ServerCode) + doc.substr(target.index);
					}
					else
					{
						widget.insertAfter(targetWidget);
						doc = doc.substr(0, target.index + target[0].length) + widgetText.replace("{#Content#}", result.ServerCode) + doc.substr(target.index + target[0].length);
					}
					BindWidget(widget);
					
					//id不空的话，表示编辑。编辑时，先要删除原先的
					if (id != "")
						WidgetDelete_OnClick();

					$("#InsertDialog").dialog("close");
				},
				"Cancel":function()
				{
					$("#InsertDialog").dialog("close");
				}
			}
		});
	}
	
	//插入widget
	var WidgetInsert_OnClick = function()
	{
		ShowPropertyDialog();
	};
	
	//编辑widget
	var WidgetEdit_OnClick = function()
	{
		ShowPropertyDialog($("#WidgetSelect").data("Source").attr("id"));
	};
	
	//删除widget
	var WidgetDelete_OnClick = function()
	{
		//文档中删除
		var sourceID = $("#WidgetSelect").data("Source").attr("id");
		var sourceRe = new RegExp("(<!-- TemplateBeginEditable name=\".*\" -->\\s*)?<widget id=\"" + sourceID + "\"(.|\\s)*?</widget>(\\s*<!-- TemplateEndEditable -->)?", "g");
		var source = sourceRe.exec(doc);
		doc = doc.substr(0, source.index) + doc.substr(source.index + source[0].length);
		
		//css中删除
		var guid = $("#WidgetSelect").data("Source").attr("guid");
		if (guid != null && doc.indexOf(guid) == -1)
		{
			var re = new RegExp("/\\*\\s*Start:([\\w-]+)\\{ID:\"" + guid + "\"(.|\\s)*?/\\*\\s*End:\\1\\s*\\*/", "g");
			var f = re.exec(style);
			if (f != null)
				style = style.substr(0, f.index) + style.substr(f.index + f[0].length);
		}
		
		//视图中删除
		$("#WidgetSelect").data("Source").remove();
		$("#WidgetSelect").hide();
		$("#WidgetTool").hide();
	};
	
	//暂停或者进行可视编辑
	var WidgetPause_OnClick = function()
	{
		var me = $(this);
		if (status == "Play")
		{
			me.attr("src", me.attr("src").replace("pause", "play"));
			status = "Pause";
		}
		else
		{
			me.attr("src", me.attr("src").replace("play", "pause"));
			status = "Play";
		}
	};
	
	//恢复
	var WidgetRevert_OnClick = function()
	{
		SetStatusMessage(dict.find("Word[Name=working] " + lang).text());
	
		$.ajax(
		{
			url : _veChannelPath + "ajax_revert.aspx?Path=" + encodeURIComponent(_veCurPage),
			type : "POST",
			data : {},
			error : function(request)
			{
				if (request.status == 404)
					Alert(dict.find("Word[Name=config_file_not_exist] " + lang).text());
				else
					Alert(dict.find("Word[Name=operation_fail] " + lang).text());
				SetStatusMessage();
			},
			success : function(data)
			{
				Alert(dict.find("Word[Name=operation_success] " + lang).text(), function(){window.location.reload();}, this);
				SetStatusMessage();
			}
		});
	};
	
	//保存改动
	var WidgetSave_OnClick = function()
	{
		var html = doc.replace(/<widget id="\w+"/g, "<widget").replace(/ guid="[\w-]+"/g, "");
		if (style.length > 0)
		{
			if (html.indexOf(cssPath) == -1)
			{
				var index = html.indexOf("</head>");
				html = html.substr(0, index) + "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + cssPath + "\">" + html.substr(index);
			}
		}
		else
		{
			html = html.replace("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + cssPath + "\">", "");
		}
		
		var data = "Html=" + encodeURIComponent(html);
		data += "&PagePath=" + encodeURIComponent(_veCurPage);
		if (style.length > 0)
		{
			data += "&Css=" + encodeURIComponent(style);
			data += "&CssPath=" + encodeURIComponent(cssPath);
		}
		
		SetStatusMessage(dict.find("Word[Name=working] " + lang).text());
	
		$.ajax(
		{
			url : _veChannelPath + "ajax_save.aspx",
			type : "POST",
			data : data,
			error : function(request)
			{
				Alert(dict.find("Word[Name=operation_fail] " + lang).text());
				SetStatusMessage();
			},
			success : function(data)
			{
				Alert(dict.find("Word[Name=operation_success] " + lang).text());
				SetStatusMessage();
			}
		});
	};

	var Init = function()
	{
		//初始化变量
		var js = document.getElementsByTagName("script");
		lang = _curImagePath.match(/\/\w+(?=\/image\/$)/).toString().substr(1);
		veTemplatePath = js[js.length-1].src.substring(0,js[js.length-1].src.lastIndexOf("/")+1).replace("/js/", "/");
		veImagePath = veTemplatePath + "S01/" + lang + "/image/";
		cssPath = _veCurPage.replace(/\/[\w\.]*$/g, "/widget.css");
		
		//初始化页面元素
		$("body").append("<style>\
					#StatusDialog{margin:5px;padding:5px 5px 5px 20px;border:1px solid #666;max-width:200px;line-height:30px;color:#900;text-align:left;background:url(" + veImagePath + "working.gif) left center no-repeat #EEE}\
					#WidgetSelect{display:none;position:absolute;top:0;left:0;width:0;height:0;border:1px solid #F00;cursor:move;filter:alpha(Opacity=50);-moz-opacity:0.5;opacity:0.5;background:#000}\
					#WidgetIndicator{display:none;position:absolute;top:0;left:0;border:2px dashed #CCC;height:10px}\
					#WidgetTool{display:none;position:absolute;top:0;left:0;border:1px solid #CCC;font-size:0;background:#FFF}\
					#WidgetTool img{cursor:pointer}\
					#WidgetPageTool{position:fixed;top:0;right:0;border:1px solid #CCC;font-size:0;background:#FFF}\
					#WidgetPageTool img{cursor:pointer}\
					.WidgetText{color:#000;background:#FFF}\
					</style>\
					<div id='InsertDialog' style='display:none'></div>\
					<div id='WidgetIndicator'></div>\
					<div id='WidgetSelect'></div>\
					<div id='WidgetTool'><img id='WidgetInsert' src='" + veImagePath + "insert.png'><img id='WidgetEdit' src='" + veImagePath + "edit.png'><img id='WidgetDelete' src='" + veImagePath + "delete.png'></div>\
					<div id='WidgetPageTool'><img id='WidgetPause' src='" + veImagePath + "pause.png'><img id='WidgetRevert' src='" + veImagePath + "revert.png'><img id='WidgetSave' src='" + veImagePath + "save.png'></div>");

		//加载模板文档
		LoadTemplate();
		
		//加载词典
		LoadDict();
		
		//加载css
		LoadCss();

		//绑定事件
		BindWidget($("widget"));
		BindText($("text"));
		BindWidgetSelect($("#WidgetSelect"));
		$("#WidgetInsert").click(WidgetInsert_OnClick);
		$("#WidgetEdit").click(WidgetEdit_OnClick);
		$("#WidgetDelete").click(WidgetDelete_OnClick);
		$("#WidgetSave").click(WidgetSave_OnClick);
		$("#WidgetPause").click(WidgetPause_OnClick);
		$("#WidgetRevert").click(WidgetRevert_OnClick);
	}
	
	Init();
}

InitVEdit();